package top.lishuoboy.cors.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/** 1.跨域全局配置方式-Filter(全适用) */
@Slf4j
@Configuration
public class CorsFilter implements Filter {

    /**
     * <h2>【1.跨域全局配置方式-Filter(全适用)：重写 Filter.doFilter()，设置 res.setHeader("Access-Control-Allow-Origin", "*") 等响应头参数】</h2>
     * <h3>【4种跨域实现方式 及 优先级（从高到低）】https://blog.csdn.net/lishuoboy/article/details/141123142</h3>
     * <div> 1.跨域全局配置方式-Filter(全适用)：重写 Filter.doFilter()，设置 res.setHeader("Access-Control-Allow-Origin", "*") 等响应头参数</div>
     * <div> 2.跨域全局配置方式-SpringMvc    ：重写 WebMvcConfigurer.addCorsMappings()，设置 registry.addMapping("/**").allowedOrigins("*")等响应头参数（只对SpringMvc写法生效，对原生Servlet不生效）</div>
     * <div> 3.跨域单个配置方式-WebServlet   ：设置 res.addHeader("Access-Control-Allow-Origin", "*") 等响应头参数</div>
     * <div> 4.跨域单个配置方式-SpringMvc    ：添加 @CrossOrigin注解，设置origins等响应头参数（只对SpringMvc写法生效，对原生Servlet不生效）</div>
     * <h3>【其他参考文章】</h3>
     * <div> 1. @CrossOrigin详细参数说明 https://www.jb51.net/program/305133q17.htm</div>
     * <div> 2. SpringBoot处理跨域请求的四种方法 https://www.jb51.net/program/30726178v.htm</div>
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if (req.getRequestURI().startsWith("/ajax")) {
            log.warn("method==【{}】, name==【{}】, header.origin==【{}】, Access-Control-Request-Method==【{}】, Access-Control-Request-Headers==【{}】", req.getMethod(), req.getParameter("name"), req.getHeader("Origin"), req.getHeader("Access-Control-Request-Method"), req.getHeader("Access-Control-Request-Headers"));
        } else {
            log.info("req.URI==【{}】", req.getRequestURI());
        }

//        HttpServletResponse res = (HttpServletResponse) response;
//        res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));                                  //【跨域配置】[必需]               允许请求源  ：默认值 无，配置"*"允许所有。
//        // 如果是复杂请求的预检请求（判断逻辑同SpringMvc），设置以下响应头，且没必要执行其它过滤器链 chain.doFilter(request, response);
//        if (req.getMethod().equalsIgnoreCase("OPTIONS") && !ObjUtil.hasNull(req.getHeader("Origin"), req.getHeader("Access-Control-Request-Method"))) {
//            res.setHeader("Access-Control-Allow-Methods", req.getHeader("Access-Control-Request-Method"));      //【跨域配置】[有复杂请求方法时必需]  允许请求方法：默认值 无，配置 "*"，允许所有
//            res.setHeader("Access-Control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));     //【跨域配置】[有复杂请求头时必需]    允许请求头 ： 默认值 无，配置 "*"，允许所有
//            res.setHeader("Access-Control-Max-Age", "5");                                                       //【跨域配置】[非必需]             预检缓存时长： 默认值 依赖客户端。EDGE浏览器默认值为3秒。【注意浏览器不要禁用缓存，否则不生效】
//            return;
//        }
        chain.doFilter(request, response);
    }
}
